package logic

import (
	"context"
	"net/http"
	"path/filepath"
	"post/pkg"

	"post/api/internal/svc"
	"post/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadLogic) Upload(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	file, m, err := req.FormFile("image")
	if err != nil {
		return nil, err
	}
	ext := filepath.Ext(m.Filename)
	if ext != ".jpg" && ext != ".png" {
		return &types.Response{
			Message: "图片格式只能是jpg和png",
			Code:    500,
			Data:    nil,
		}, nil
	}
	if m.Size >= 5*1024*1024 {
		return &types.Response{
			Message: "图片大小不能超过5M",
			Code:    500,
			Data:    nil,
		}, nil
	}
	upload, err := pkg.Upload(file, m)
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    500,
			Data:    nil,
		}, nil
	} else {

		return &types.Response{
			Message: "图片上传成功",
			Code:    200,
			Data:    upload,
		}, nil
	}

}
